<template>
  <div style="display: flex; flex-direction: column; height: 100%">
    <SearchList>
      <template #actions>
        <a-button size="small" type="primary" @click="editVisible = true">新建</a-button>
      </template>
    </SearchList>
    <BoliTabel ref="tableRef" :columns="columns" api="/admin/user/list" :params="tableParams">
      <template #avatar="{ record }">
        <img v-if="record.avatar" :src="record.avatar" alt="头像" class="avatar" />
        <span v-else>未设置头像</span>
      </template>
      <template #action="{ record }">
        <div class="action-buttons">
          <a-button type="link" size="small" @click="editRef.edit(record)">
            <EditOutlined />
            编辑
          </a-button>
          <a-button type="link" size="small" danger @click="handleDelete(record)">
            <DeleteOutlined />
            删除
          </a-button>
        </div>
      </template>
    </BoliTabel>
    <EditAccount ref="editRef" v-model:open="editVisible" @success="flushTabel" />
  </div>
</template>

<script setup>
import BoliTabel from '@/components/BoliTable/index.vue'
import { columns } from './data'
import EditAccount from './EditAccount.vue'

defineOptions({ name: 'Account' })

const tableParams = reactive({
  keywords: null,
})

const tableRef = ref(null) // 表格实例
const editRef = ref(null) // 编辑组件实例
const editVisible = ref(false)

// 删除用户
function handleDelete(record) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 "${record.nickName}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      try {
        await httpRequest(`/admin/user/delete`, { id: record.id })
        message.success('删除成功')
        tableRef.value?.refresh()
      }
      catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 刷新表格数据
function flushTabel() {
  tableRef.value?.refresh()
}
</script>

<style lang="less" scoped>
.avatar {
  width: 30px;
  height: 30px;
  object-fit: cover;
  border-radius: 50%;
}

.action-buttons {
  display: flex;
  gap: 8px;

  .ant-btn-link {
    height: auto;
    padding: 0;

    &:hover {
      transform: scale(1.1);
    }
  }
}
</style>
